<template>

  <div class="top">
    <van-search v-model="value"
                show-action
                placeholder="请输入搜索关键词"
                @search="onSearch"
                @cancel="onCancel"
                style="border-radius: 10px"
    />
  </div>
  <div class="fire" v-if="flag">
    <div class="title">热搜
      <van-icon name="fire" style="color:orangered"/>
    </div>
  </div>
  <div class="box" v-if="flag">
    <div class="item" v-for="(item,i) in fire" :key="i" @click="navTo(item)">{{ item.name }}</div>
  </div>

  <div class="list" v-if="!flag">
    <div class="result" v-for="(item,i) in result" :key="i" @click="navTo(item)">{{ item.name }}</div>
  </div>
</template>

<script setup>
import {
  ref, onMounted,
  inject
} from "vue";
import {useRouter} from "vue-router";
import {showNotify} from "vant";

const axios = inject("axios")
const value = ref("")
const flag = ref(true)
const router = useRouter()
const fire = ref([])
const result = ref([])
onMounted(() => {
  axios.get('goods/search/fire?p=1&s=10').then(res => {
    fire.value = res.data?.data
  }).catch(err => {
    showNotify({type: 'danger', message: "网络异常"})
  })
})

const onCancel = () => {
  router.back()
}
const onSearch = () => {
  if(value.value.trim()!==""){
     flag.value = false
  axios.get('goods/search?name=' + value.value.trim()).then(res => {
    result.value = res.data?.data
  }).catch(err => {
    showNotify({type: 'danger', message: "网络异常"})
  })
  }
  else showNotify({type: 'danger', message: "请输入搜索关键词"})

}

const navTo = e => {
  axios.get('goods/visit?id=' + e.id).catch(err => showNotify({type: 'danger', message: "网络异常"})
  )
  router.push('/item/' + e.id)
}
</script>

<style scoped lang="less">
.top {
  width: 90%;
  margin: 10px;

}

.fire {
  width: 90%;
  margin: 10px;
  text-align: start;
  line-height: 20px;
  font-size: 14px;
  color: black;
}

.box {
  width: 90%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: start;

  .item {
    margin-right: 10px;
    margin-top: 10px;

    font-size: 14px;
    max-width: 40%;
    text-align: start;
    line-height: 20px;
    background-color: #ffffff;
    padding: 10px;
    border-radius: 10px;
    color: #606266;

  }
}

.list {
  margin: 0 auto;
  width: 90%;
  background-color: #ffff;
  border-radius: 10px;

  .result {
    width: 100%;
    text-indent: 1em;
    text-align: start;
    height: 50px;
    line-height: 50px;
    color: #409EFF;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
    overflow: hidden;
    padding: 0 10px;
    box-sizing: border-box;
  }
}


</style>